package tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPServer {
    private ServerSocket socket;
    public TCPServer(int port) throws IOException {
        socket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动：");
        while(true) {
            //建立连接
            Socket client = socket.accept();
            //打印连接信息
            System.out.printf("[%s,%d]已连接\n", client.getInetAddress(), client.getPort());

            new Thread(()->{
                try(InputStream inputStream = client.getInputStream();
                    OutputStream outputStream = client.getOutputStream()) {
                    //通过Scanner 在输入流中读读数据
                    Scanner in = new Scanner(inputStream);

                    PrintWriter printWriter = new PrintWriter(outputStream);
                    while(true) {
                        if(!in.hasNext()) {
                            //读取完毕说明连接断开
                            break;
                        }
                        //读取数据
                        String request = in.nextLine();
                        //构造响应
                        String response = request;
                        printWriter.println(response);
                        printWriter.flush();
                        //打印日志
                        System.out.printf("[%s,%d] req: %s rqs: %s\n", client.getInetAddress(), client.getPort(), request, response);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).start();

        }
    }

    public static void main(String[] args) throws IOException {
        TCPServer server = new TCPServer(8090);
        server.start();
    }
}
